// ... (imports and useState hooks remain the same)
import React, { useState } from 'react';
import './App.css';
import { callKimiApi } from './utils/kimi';
import type { ResumeData } from './types';


function App() {
  const [apiKey, setApiKey] = useState('');
  const [file, setFile] = useState<File | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [parsedData, setParsedData] = useState<ResumeData | null>(null);
  const [errorMessage, setErrorMessage] = useState('');

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      setFile(e.target.files[0]);
    }
  };

  const handleParse = async () => {
    // ... (handleParse function remains the same)
    if (!apiKey) {
      setErrorMessage('请输入你的Kimi API Key。');
      return;
    }
    if (!file) {
      setErrorMessage('请先选择一个简历文件 (PDF格式)。');
      return;
    }
    setIsLoading(true);
    setErrorMessage('');
    setParsedData(null);
    try {
      const resumeJson = await callKimiApi(apiKey, file);
      setParsedData(resumeJson);
      chrome.storage.local.set({ resumeData: resumeJson }, () => {
        console.log('AI解析并保存简历数据成功！');
      });
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : '发生未知错误');
    } finally {
      setIsLoading(false);
    }
  };

  // 【新增的函数】
  const handleFill = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0] && tabs[0].id) {
        chrome.tabs.sendMessage(tabs[0].id, { action: 'fillForm' }, (response) => {
          if (chrome.runtime.lastError) {
            alert('无法连接到页面，请刷新页面后重试。');
          } else {
            console.log(response?.status);
          }
        });
      }
    });
  };

  return (
    <div className="app-container">
      {/* ... (AI解析部分的 JSX 保持不变) */}
      <h1>AI 简历一键解析</h1>
      <p className="description">上传PDF简历，让AI自动提取信息并保存。</p>
      <div className="input-group">
        <label>Kimi API Key:</label>
        <input type="password" value={apiKey} onChange={(e) => setApiKey(e.target.value)} placeholder="请输入你的API Key" />
      </div>
      <div className="input-group">
        <label>选择简历文件:</label>
        <input type="file" accept=".pdf" onChange={handleFileChange} />
      </div>
      <button onClick={handleParse} disabled={isLoading}>
        {isLoading ? '正在解析中...' : '开始解析并保存'}
      </button>
      {errorMessage && <p className="error">{errorMessage}</p>}
      {parsedData && (
        <div className="result-preview">
          <h3>解析结果预览:</h3>
          <pre>{JSON.stringify(parsedData, null, 2)}</pre>
        </div>
      )}

      {/* --- 【新增的部分】 --- */}
      <hr style={{ margin: '20px 0' }} />
      <h2>开始填写</h2>
      <p className="description">请先确保上方已成功解析并保存简历。</p>
      <button onClick={handleFill} style={{ backgroundColor: '#28a745' }}>
        一键填写当前页面
      </button>
    </div>
  );
}

export default App;